const puppeteer = require('puppeteer');
const base = `https://movie.douban.com/subject//`;
const doubanId = '30269016'
const videoBase = `https://movie.douban.com/trailer/257285/#content`;

const sleep = time=> new Promise(resolve => {
  setTimeout(resolve, time);
});

(async ()=>{
  console.log('Start target pages');
  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    dumpio: false
  });
  const page = await browser.newPage();
  await page.goto(base + doubanId, {
    waitUntil: 'networkidle2'
  });
  await sleep(1000);



  const result = await page.evaluate(()=>{
    const $ = window.$;
    var it = $('.related-pic-video');
    if (it && it.length > 0){
      var link = it.attr('href');
      var title = it.attr('title');
      // var cover = it.find('img').attr('src');
      var cover = it.attr('style').replace(`background-image:url(`,``).replace(')','');

      return {
        link,
        cover,
        title
      }
    }

    return {};
  })
  let video;

  if (result.link) {
    await page.goto(result.link, {
      waitUntil: 'networkidle2'
    })
    await sleep(2000);
    video = await page.evaluate(()=>{
      const $ = window.$
      var it = $('source')
      if (it && it.length > 0) {
        return it.attr('src');
      }
      return ''
    })
  }
  const data = {
    video,
    doubanId,
    cover: result.cover,
    title: result.title
  };
  browser.close();
  // console.log(result);
  process.send(data);
  process.exit(0);
})();
